import sys
import os
import json

from errors import *
from events import *

class Scenario(object):
    STATE_INITIALIZING = 0
    STATE_PLAYING = 1
    STATE_LOSS = 2
    STATE_WIN = 3

    def __init__(self, path):
        self.decideToExit(path)

        if '~' in path:
            path = os.path.expanduser(path)

        path = os.path.abspath(path)
        self.root = path

        try:
            with open(
                    os.path.sep.join([self.root, 'main.json']), 'rb') as infile:
               data = json.loads( infile.read() ) 
        except IOError as ioe:
            raise ScenarioNotFoundError(ioe)

        for key, val in data.iteritems():
            self.__setattr__(key, val)

        self.state = self.STATE_INITIALIZING 


    def setState(self, state):
        if self.state == STATE_INITIALIZING and state == STATE_PLAYING:
            raise OutputEvent()

        self.state = state


    def processInput(self, text):
        self.decideToExit(text) 


    def decideToExit(self, text, beforeExit=None):
        if text in ['quit', 'q', 'exit']:
            raise ExitEvent(beforeExit=beforeExit)


    def getWelcomeText(self, stream=sys.stdout):
        return '\n%s\n\n---Press return to get started!---' % self.welcomeText


    def __str__(self):
        return self.root
